package com.google.code.server4j.connector.nio;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.google.code.server4j.log.Log;

public class NioProcessorHandler {
	private ConcurrentHashMap<NioSocket, NioProcessor> connect = new ConcurrentHashMap<NioSocket, NioProcessor>();
	private ConcurrentLinkedQueue<NioProcessor> cycledProcessors = new ConcurrentLinkedQueue<NioProcessor>();
	
	
	public void process(NioSocket socket) {
		NioProcessor processor = null;
		try {
			processor = connect.remove(socket);
			if(processor == null) {
				processor = new NioProcessor();
			}
			SocketConnectState state = processor.process(socket);
			if(state == SocketConnectState.EXPECT_NEXT_CONNECT) {
				connect.put(socket, processor);
				socket.setState(SocketConnectState.EXPECT_NEXT_CONNECT);
				socket.setLastVisitTime(System.currentTimeMillis());
				socket.getSelectorManager().registerEvent(socket);
				
			} else if(state == SocketConnectState.KEEP_ALIVE) {
				release(socket, processor);
				socket.getSelectorManager().registerEvent(socket);
				socket.setLastVisitTime(System.currentTimeMillis());
				socket.setState(SocketConnectState.KEEP_ALIVE);
				
			} else if(state == SocketConnectState.CLOSE) {
				release(socket, processor);
				socket.setState(SocketConnectState.CLOSE);
			}
			
		} catch(Exception e) {
			Log.error(e.getMessage(),e);
		}
//		NioProcessor processor = new NioProcessor();
//		processor.process(socket);
	}
	
	public void release(NioSocket socket,NioProcessor processor) {
		connect.remove(socket);
		processor.cycle();
		cycledProcessors.offer(processor);
	}
}
